package cn.lxh.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.lxh.basic.exception.BusinessException;
import cn.lxh.basic.utils.DateUtil;
import cn.lxh.basic.utils.HttpUtils;
import cn.lxh.basic.utils.UUIDUtils;
import cn.lxh.system.domain.AccessToken;
import cn.lxh.system.domain.WxtemplateReq;
import cn.lxh.system.domain.wxDataReq;
import cn.lxh.system.service.WxAccountService;
import cn.lxh.user.constant.WxPublicConstant;
import cn.lxh.user.domain.WxPublicContent;
import cn.lxh.user.domain.WxPublicOrder;
import cn.lxh.user.domain.WxPublicTemplat;
import cn.lxh.user.domain.WxPublicTouser;
import cn.lxh.user.enums.WxPublicEnum;
import cn.lxh.user.mapper.WxPublicOrderMappper;
import cn.lxh.user.mapper.WxPublicTemplatMapper;
import cn.lxh.user.mapper.WxPublicTouserMappper;
import cn.lxh.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName WxAccountServiceImpl
 * @Description 微信公众号
 * @Author luoxiaohu
 * @Date 2023/7/18 17:37
 * @Vsersion 1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class WxAccountServiceImpl implements WxAccountService {

    @NacosValue(value = "${wxAccesstoken}",autoRefreshed = true)
    private String wxAccesstoken;

    @NacosValue(value = "${appid}",autoRefreshed = true)
    private String appid;


    @NacosValue(value = "${appsecret}",autoRefreshed = true)
    private String appsecret;

    @NacosValue(value = "${wxSendUrl}",autoRefreshed = true)
    private String wxSendUrl;

    @NacosValue(value = "${templateIdOne}",autoRefreshed = true)
    private String templateIdOne;

    private final WxuserMapper wxuserMapper;

    private final WxPublicOrderMappper wxPublicOrderMappper;

    private final WxPublicTemplatMapper wxPublicTemplatMapper;

    private final WxPublicTouserMappper wxPublicTouserMappper;
    @Autowired
    private RedisTemplate redisTemplate;

    private final String LOVESTARTTIME = "2016-12-11 20:40:00";


    /**
     * 获取token
     * @return
     */
    @Override
    public String getWxAccessToken() {

        //api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb5cb3cec24f258ed&secret=00d735eaa51bd723d52ff3e4ce3c072f
        String url = wxAccesstoken + "?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        try {
            Object accessTokenRedis = redisTemplate.opsForValue().get("access_token");
            if (ObjectUtils.isNotEmpty(accessTokenRedis)){
                return accessTokenRedis.toString();
            }
            String info = HttpUtils.get(url);
            AccessToken accessToken = JSONObject.parseObject(info, AccessToken.class);

            if (null != accessToken){
                String token = accessToken.getAccessToken();
                redisTemplate.opsForValue().set("access_token",token,2, TimeUnit.HOURS);
                log.info("微信通知,消息推送参数{}",token);
                return token;
            }
        }catch (Exception e){
            log.info("获取微信公众号token异常：{}",e);
        }
        return null;
    }

    /**
     * 发送公共号消息
     */
    @Override
    public void sendWxSms(WxtemplateReq req) {
//        https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN\
        String wxAccessToken = getWxAccessToken();
        String url = wxSendUrl+"?access_token="+wxAccessToken;

        List<WxPublicTemplat> wxPublicTemplats = wxPublicTemplatMapper.selectAll();

        wxPublicTemplats.stream().filter(a->a.getStatus().equals(1)).forEach(a->{

            List<String> users = Arrays.asList(a.getRelationTouserId().split(","));
            //使用的tem_id
            req.setTemplate_id(a.getTemplateId());

            List<WxPublicTouser> wxPublicTousers = wxPublicTouserMappper.selectByToUsers(users);



            wxPublicTousers.forEach(b->{
                // 预创订单
                WxPublicOrder wxPublicOrder = new WxPublicOrder();
                createOrder(req,b,wxPublicOrder);
                try {
                    req.setTouser(b.getTouserId());
                    //填充信息
                    Map<String,wxDataReq> dataReqMap = creatDataMap(req.getTemplate_id(),req.getTouser());
                    req.setData(dataReqMap);
                    String jsonString = JSONObject.toJSONString(req);
                    log.info("微信公众号发送消息：{}",jsonString);
                    String postJson = HttpUtils.postJson(url, jsonString);
                    JSONObject jsonObject = JSONObject.parseObject(postJson);
                    if (!jsonObject.get("errmsg").equals("ok")){
                        throw new BusinessException("公众号发送失败");
                    }
                    wxPublicOrder.setStatus(2);
                }catch (Exception e){
                    log.info("发送微信公众号信息错误：{}",e);
                    wxPublicOrder.setStatus(0);
                }finally {
                    wxPublicOrderMappper.updateOrder(wxPublicOrder);
                }

            });

        });


    }

    /**
     * 内容的填充
     * @return
     */
    private Map<String, wxDataReq> creatDataMap(String templateId,String touser) {
        WxPublicContent wxPublicContentTem =wxPublicTouserMappper.selectContentByTemUser(templateId,touser);

        Map<String, wxDataReq> dataReqHashMap = new HashMap<>();
        dataReqHashMap.put("first",new wxDataReq(wxPublicContentTem.getFirst()));
        dataReqHashMap.put("second",new wxDataReq(wxPublicContentTem.getSecond()));
        dataReqHashMap.put("third",new wxDataReq(wxPublicContentTem.getThird()));
        dataReqHashMap.put("fourth",new wxDataReq(wxPublicContentTem.getFourth()));
        dataReqHashMap.put("fifth",new wxDataReq(wxPublicContentTem.getFifth()));
        dataReqHashMap.put("sixth",new wxDataReq(wxPublicContentTem.getSixth()));
        dataReqHashMap.put("seventh",new wxDataReq(wxPublicContentTem.getSeventh()));
        dataReqHashMap.put("eighth",new wxDataReq(wxPublicContentTem.getEighth()));
        dataReqHashMap.put("ninth",new wxDataReq(wxPublicContentTem.getNinth()));
        dataReqHashMap.put("tenth",new wxDataReq(wxPublicContentTem.getTenth()));
        dataReqHashMap.put("eleventh",new wxDataReq(wxPublicContentTem.getEleventh()));
        dataReqHashMap.put("twelfth",new wxDataReq(wxPublicContentTem.getTwelfth()));
        dataReqHashMap.put("thirteenth",new wxDataReq(wxPublicContentTem.getThirteenth()));
        dataReqHashMap.put("fourteenth",new wxDataReq(wxPublicContentTem.getFourteenth()));
        dataReqHashMap.put("fifteenth",new wxDataReq(wxPublicContentTem.getFifteenth()));

        return dataReqHashMap;

    }

    /**
     * 预创订单
     * @param req
     * @param wxPublicTouser
     * @param wxPublicOrder
     */
    private void createOrder(WxtemplateReq req,WxPublicTouser wxPublicTouser,WxPublicOrder wxPublicOrder) {
        wxPublicOrder.setOrderId(UUIDUtils.getUUID());
        wxPublicOrder.setId(null);
        wxPublicOrder.setStatus(1);
        wxPublicOrder.setTemplateId(req.getTemplate_id());
        wxPublicOrder.setCreateTime(new Date());
        wxPublicOrder.setTouserId(wxPublicOrder.getOrderId());
        wxPublicOrder.setName(wxPublicTouser.getName());
        wxPublicOrderMappper.saveWxPublicOrder(wxPublicOrder);
    }

    /**
     * 获取内容
     */
    public Boolean getApiInfo(){

        //先获取天气api 没拼接城市
        String weatherapi = WxPublicConstant.WeatherConstants.WEATHERAPI+ WxPublicConstant.WeatherConstants.WEATHER_KEY;

        List<WxPublicTemplat> wxPublicTemplats = wxPublicTemplatMapper.selectAll();

        wxPublicTemplats.forEach(a->{
            List<String> users = Arrays.asList(a.getRelationTouserId().split(","));
            List<WxPublicTouser> wxPublicTouserList =  wxPublicTouserMappper.selectByToUsers(users);


            wxPublicTouserList.forEach(b->{
                String weatherUserApi = weatherapi + "&city=" + b.getCity();

                String resInfo = null;
                try {
                    resInfo = HttpUtils.get(weatherUserApi);

                } catch (Exception e) {
                    log.info("获取天气api"+e);
                }

                JSONObject jsonObject = JSON.parseObject(resInfo);
                JSONObject jsonResult = jsonObject.getJSONObject("result");

                String city = jsonResult.getString("city");

                JSONObject jsonRealtime = jsonResult.getJSONObject("realtime");

                String temperature = jsonRealtime.getString("temperature");
                //多云
                String info = jsonRealtime.getString("info");
                //空气质量
                String aqi = jsonRealtime.getString("aqi");
                WxPublicContent wxPublicContent = new WxPublicContent();

                String tqtype = WxPublicEnum.getTqtypeByDesc(info);

                // 天气诗句
                String poetryUrl = WxPublicConstant.WeatherPoetryConstants.POETRY_URL + WxPublicConstant.WeatherPoetryConstants.POETRY_KEY +"&tqtype="+tqtype;
                String poetryInfo = null;
                try {
                    poetryInfo = HttpUtils.get(poetryUrl);
                } catch (Exception e) {
                    log.error("天气诗句获取异常",e);
                }

                JSONObject jsonpoetryObject = JSON.parseObject(poetryInfo);

                JSONObject jsonPoeresult = jsonpoetryObject.getJSONObject("result");
                String content = jsonPoeresult.getString("content");

                Date date = DateUtil.convertStrToDate(LOVESTARTTIME);
                int loveDay = DateUtil.differentDaysByMillisecond(date, new Date());

                wxPublicContent.setFirst(DateUtil.convertDateToStr(new Date(),"yyyy-MM-dd"));
                wxPublicContent.setTemplate_id(a.getTemplateId());
                wxPublicContent.setTouser_id(b.getTouserId());
                wxPublicContent.setSecond(city);
                wxPublicContent.setThird(info);
                wxPublicContent.setFourth(temperature);
                wxPublicContent.setFifth(aqi);
                wxPublicContent.setSixth(content);
//            wxPublicTouserMappper.inserIntoContent();
                wxPublicContent.setSeventh(String.valueOf(loveDay));

                Integer day =wxPublicTouserMappper.dateDiff(b.getBirthday(),b.getTouserId());
                wxPublicContent.setEighth(String.valueOf(day));
                //土味情话
                String LoveUrl = WxPublicConstant.LoveTalkConstants.LOVETALK_URL + WxPublicConstant.WeatherPoetryConstants.POETRY_KEY;
                String LoveInfo = null;
                try {
                    LoveInfo = HttpUtils.get(LoveUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                JSONObject jsonLoveObject = JSON.parseObject(LoveInfo);
                JSONObject jsonLoveresult = jsonLoveObject.getJSONObject("result");
                String Lovecontent = jsonLoveresult.getString("content");
                wxPublicContent.setNinth(Lovecontent);

                WxPublicContent wxPublicContentTem =wxPublicTouserMappper.selectContentByTemUser(a.getTemplateId(),b.getTouserId());
                if (ObjectUtils.isEmpty(wxPublicContentTem)){
                    wxPublicTouserMappper.inserIntoContent(wxPublicContent);
                }else {
                    wxPublicTouserMappper.updateIntoContent(wxPublicContent);
                }

            });



        });

        return null;
    }


}
